﻿#!/usr/bin/python

import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class MainWindow(QDialog):
    
    def __init__(self):
        super(MainWindow,self).__init__()
        
        self.threadAButton = QPushButton(self.tr('Start A'))
        self.connect(self.threadAButton, SIGNAL('clicked()'), self.startOrStopThreadA)
        self.threadBButton = QPushButton(self.tr('Start B'))
        self.connect(self.threadBButton, SIGNAL('clicked()'), self.startOrStopThreadB)
        self.quitButton    = QPushButton(self.tr('Quit'))
        self.connect(self.quitButton, SIGNAL('clicked()'),self.closeEvent)
        
        self.threadA = Thread()
        self.threadB = Thread()
        
        vbox = QVBoxLayout()
        vbox.addWidget(self.threadAButton)
        vbox.addWidget(self.threadBButton)
        vbox.addWidget(self.quitButton)
        self.setLayout(vbox)
        
    def startOrStopThreadA(self):
        if self.threadA.isRunning():
            self.threadA.stop()
            self.threadAButton.setText('Start A')
        else:
            self.threadA.start()
            self.threadAButton.setText('Stop A')
    def startOrStopThreadB(self):
        if self.threadB.isRunning():
            self.threadB.stop()
            self.threadBButton.setText('Start B')
        else:
            self.threadB.start()
            self.threadBButton.setText('Stop B')
        
        
    def closeEvent(QCloseEvent):
        
        def __init__(self):
            # super(closeEvent,self).__init__()
            self.threadA.stop()
            self.threadB.stop()
            self.threadA.wait()
            self.threadB.wait()
            # QCloseEvent.accept()
class Thread(QThread):
    def __init__(self):
        super(Thread, self).__init__()
        self.stopped = False
        # self.message 
        
    def run(self):
        while not stopped:
            print 'run'
    def stop(self):
        self.stopped = True
        
app = QApplication(sys.argv)
main = MainWindow()
main.show
sys.exit(app.exec_())